<template>
    <div class="integralPay">
        <div class="integralPay-header">
            <div class="left" @click="handleBack">
                <el-icon>
                    <ArrowLeft style="font-size:24px" />
                </el-icon>
                <span class="leftBack">返回</span>
            </div>
            <div class="header-center">支付</div>
        </div>
        <!-- 订单信息 -->
        <div class="integralPay-order">
            <div class="order-title">订单信息</div>
            <div class="order-content">
                <div class="order-content-item">
                    <div class="order-content-left">
                        <div class="order-content-left-img">
                            <img :src="orderInfo.tutorInfo?.avatar || ''" alt="">
                        </div>
                        <div class="order-content-title">
                            {{ orderInfo.tutorInfo?.name || '' }}
                        </div>
                    </div>
                    <div class="order-content-right">
                        <div class="currency">
                            <span class="currency-name">人民币（CNY）</span>
                            <span class="currency-value">¥{{ orderInfo.totalAmount || 0 }}</span>
                        </div>
                    </div>
                </div>
            </div>
            <div class="integral-info">
                <div class="integral-info-left">
                    云豆（共{{ userBeans || 0 }}个）
                </div>
                <div class="integral-info-right" @click="handleIntegralModal">
                    去选择>
                </div>
            </div>
            <div class="total-price">
                <div class="total-price-left">
                    小计：¥{{ orderInfo.totalAmount || 0 }}
                </div>
            </div>
        </div>
        <!-- 金额信息 -->
        <div class="amount-info">
            <div class="amount-info-right">
                <div class="total-amount-item">
                    <div class="total-amount-item-left">总金额:</div>
                    <div class="total-amount-item-right">¥{{ orderInfo.totalAmount || 0 }}</div>
                </div>
                <div class="total-amount-item">
                    <div class="total-amount-item-left">优惠金额:</div>
                    <div class="total-amount-item-right">¥{{ discountAmount }}</div>
                </div>
                <div class="total-amount-item">
                    <div class="total-amount-item-left">应付金额:</div>
                    <div class="total-amount-item-right total-amount-item-right-red">¥{{ finalAmount }}</div>
                </div>
            </div>  
        </div>
        <!-- 支付方式 -->
        <div class="payment-method">
            <div class="method-header">
                <div class="payment-amount-title">
                    应付金额:
                    <span class="payment-amount-title-red">¥{{ finalAmount }}</span>
                </div>
                <div class="payment-amount-right">
                    如有疑问，请咨询：
                    <span class="payment-amount-right-phone">400-888-8888</span>
                </div>
            </div>
            <!-- <div class="payment-method-container">
                <div class="payment-method-item" :style="radio === '1' ? 'border: 1px solid #126983;' : ''" @click="handleRadio('1')">
                    <div class="payment-method-item-left">
                        <el-radio fill="#126983" v-model="radio" label="1" size="large">
                            <div class="payment-method-item-right">
                                <img src="~@/static/zhifubao.png" alt="">
                                支付宝
                            </div>
                        </el-radio>
                    </div>
                </div>
                <div class="payment-method-item" :style="radio === '2' ? 'border: 1px solid #126983;' : ''" @click="handleRadio('2')">
                    <div class="payment-method-item-left">
                        <el-radio fill="#126983" v-model="radio" label="2" size="large">
                            <div class="payment-method-item-right">
                                <img src="~@/static/weixinPay.png" alt="">
                                微信
                            </div>
                        </el-radio>
                    </div>  
                </div>  
                <div class="submit-pay">
                    立即支付
                </div>
            </div> -->

            <div class="payment-options">
                <div class="payment-option" :class="{ active: paymentMethod === 'alipay' }" @click="paymentMethod = 'alipay'">
                    <div class="radio-button">
                        <div class="inner-circle" v-if="paymentMethod === 'alipay'"></div>
                    </div>
                    <div class="payment-icon alipay"></div>
                    <span>支付宝</span>
                    </div>
                    <div class="payment-option" :class="{ active: paymentMethod === 'wechat' }" @click="paymentMethod = 'wechat'">
                    <div class="radio-button">
                        <div class="inner-circle" v-if="paymentMethod === 'wechat'"></div>
                    </div>
                    <div class="payment-icon wechat"></div>
                    <span>微信</span>
                </div>
                <div class="submit-pay" @click="handlePayment">
                    立即支付
                </div>
            </div>
        </div>
        <!-- 云豆选择弹窗 -->
        <el-dialog v-model="beanDialogVisible" title="选择云豆使用量" width="400px" center>
            <div class="bean-dialog-content">
            <p class="bean-description">云豆抵扣说明：10豆=1元（人民币），抵扣使用需按照10的整数倍使用！</p>
            <el-select v-model="selectedBeans" placeholder="请选择" style="width: 100%">
                <el-option v-for="item in beanOptions" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
            </el-select>
            </div>
            <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="confirmBeanSelection">确定</el-button>
            </div>
            </template>
        </el-dialog>
  


        <!-- 支付弹窗 -->
        <el-dialog v-model="paymentDialogVisible" :title="paymentMethod === 'alipay' ? '支付宝支付' : '微信支付'" width="400px" center>
            <div class="payment-dialog-content">
                <div class="qr-code" v-loading="payLoading">
                    <img v-if="qrCodeDataUrl" :src="qrCodeDataUrl" alt="支付二维码" />
                </div>
                <p>扫描二维码完成支付</p>
                <div class="payment-amount">¥{{ finalAmount.toFixed(2) }} CNY</div>
            </div>
        </el-dialog>

        <!-- 支付成功弹窗 -->
        <el-dialog v-model="successDialogVisible" width="400px" center>
            <div class="success-dialog-content">
                <div class="success-icon">
                <el-icon color="#FFFF" :size="40"><Check /></el-icon>
                </div>
                <h3>支付成功</h3>
                <p>付款金额：¥{{ finalAmount.toFixed(2) }}</p>
                <el-button type="primary" @click="goToOrder">查看订单</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script setup>
import { ref, computed, onMounted } from 'vue';
import QRCode from 'qrcode';
import { useRouter } from 'vue-router';
import { usePaymentStore } from '@/stores/Payment';
import { myOrderAdd, myOrderDetail } from "@/service/personalCenter";
import { ElMessage } from 'element-plus';
import { useUserStore } from "@/stores/User";

const userStore = useUserStore();

const router = useRouter();
const paymentStore = usePaymentStore();
const orderInfo = ref({});
const radio = ref('1');
// 支付方式
const paymentMethod = ref('');
const beanDialogVisible = ref(false);
const paymentDialogVisible = ref(false);
const successDialogVisible = ref(false);
const userBeans = ref(userStore.personalDetailInfo?.point_num); // 用户拥有的云豆数量
// 选择的云豆数量
const selectedBeans = ref(''); // 选择的云豆数量
const payLoading = ref(false);
const qrCodeDataUrl = ref(''); // 二维码图片URL
const orderId = ref(null); // 订单ID用于轮询
const pollTimer = ref(null); // Add missing poll timer ref

onMounted(() => {
    // 从Pinia store中获取支付信息
    if (paymentStore.payInfo) {
        orderInfo.value = paymentStore.payInfo;
    } else {
        // 如果没有支付信息，返回上一页
        ElMessage.warning('支付信息不存在，请重新选择服务');
        router.back();
    }
});

const handleIntegralModal = () => {
    beanDialogVisible.value = true;
}

const handlePayment = () => {
    console.log('支付方式:', paymentMethod.value);
    console.log('支付金额:', finalAmount.value);
    if(paymentMethod.value === 'alipay') {
        paymentDialogVisible.value = false;
    } else if(paymentMethod.value === 'wechat') {
        paymentDialogVisible.value = true;
    } else if(selectedBeans.value === '') {
        ElMessage.warning('请选择支付方式');
        return;
    }
    
    // 判断是否使用云豆将价格全部抵消
    let payway = paymentMethod.value === 'alipay' ? 1 : 2; // 默认支付方式
    
    // 如果最终金额为0，说明已经被云豆全部抵消，设置为积分兑换
    if (finalAmount.value === 0) {
        payway = 3; // 3.积分兑换
    }
    
    const params={
        goodsid: orderInfo.value.tutorInfo.id,
        number: orderInfo.value.hours,
        appoint_time: orderInfo.value.selectedTime,
        origin: 1,
        payway: payway, // 1.支付宝，2.微信，3.积分兑换
        type: 3,
        point: Number(selectedBeans.value)
    }
    console.log(params, 'params')
    payLoading.value = true
    myOrderAdd(params).then(res=>{
        if(res.code === '000000') {
            payLoading.value = false;
            
            // 存储订单ID用于轮询
            if (res.data && res.data.id) {
                orderId.value = res.data.id;
            }
            if(params.payway === 3) {
                paymentMethod.value = ''
                successDialogVisible.value = true;
                return;
            }
            
            // 假设接口返回的微信支付URL在res.data.url中
            if (paymentMethod.value === 'wechat' && res.data && res.data.url) {
                // 生成二维码
                QRCode.toDataURL(res.data.url, { width: 200 })
                .then(url => {
                    
                    qrCodeDataUrl.value = url;
                    // 开始轮询订单状态
                    startPollOrderStatus();
                })
                .catch(err => {
                    console.error('生成二维码失败:', err);
                });
            } else if(paymentMethod.value === 'alipay') {
                // 支付宝支付
                window.open(res.data.url, '_blank');
            }
        } else {
            ElMessage.error('下单失败，请重试！')
        }
    })
}

// 轮询订单状态
const startPollOrderStatus = () => {
  // 清除可能存在的定时器
  if (pollTimer.value) {
    clearInterval(pollTimer.value);
  }
  
  // 设置轮询间隔，每2秒查询一次
  pollTimer.value = setInterval(() => {
    if (!orderId.value || !paymentDialogVisible.value) {
      clearInterval(pollTimer.value);
      return;
    }
    
    checkOrderStatus();
  }, 2000);
}

// 检查订单状态
const checkOrderStatus = () => {
  myOrderDetail({ id: orderId.value }).then(res => {
    console.log('订单状态:', res);
    if (res.code === '000000') {
      // 订单状态: 1-待支付, 2-已完成, 3-已关闭, 4-已取消
      if (res.data && res.data.status === 2) {
        // 支付成功，停止轮询
        clearInterval(pollTimer.value);
        // 关闭支付码弹窗
        paymentDialogVisible.value = false;
        // 显示支付成功弹窗
        successDialogVisible.value = true;
        ElMessage.success('支付成功');
      } else if (res.data && (res.data.status === 3 || res.data.status === 4)) {
        // 订单已关闭或已取消，停止轮询
        clearInterval(pollTimer.value);
        paymentDialogVisible.value = false;
        ElMessage.warning('订单已关闭或已取消');
      }
    }
  }).catch(err => {
    console.error('查询订单状态失败:', err);
  });
}

const handleClose = () => {
  paymentDialogVisible.value = false;
  if (pollTimer.value) {
    clearInterval(pollTimer.value);
  }
}

onBeforeUnmount(() => {
    if (pollTimer.value) {
      clearInterval(pollTimer.value);
    }
});

const confirmBeanSelection = () => {
    beanDialogVisible.value = false;
    // 确认使用云豆后重新计算金额
}

// 计算属性
const selectedBeansAmount = computed(() => {
    return selectedBeans.value ? parseInt(selectedBeans.value) / 10 : 0;
});

const discountAmount = computed(() => {
    return selectedBeansAmount.value;
});

const finalAmount = computed(() => {
    // 将金额转换为整数（分）进行计算，避免浮点数精度问题
    const totalInCents = Math.round((orderInfo.value?.totalAmount || 0) * 100);
    const discountInCents = Math.round(discountAmount.value * 100);
    // 计算结果再转回元
    return (totalInCents - discountInCents) / 100;
});

// 云豆选项
const beanOptions = ref([
    { value: '10', label: '10个云豆 (抵扣1元)' },
    { value: '100', label: '100个云豆 (抵扣10元)' },
    { value: '200', label: '200个云豆 (抵扣20元)' },
    { value: '500', label: '500个云豆 (抵扣50元)' },
    { value: '1000', label: '1000个云豆 (抵扣100元)' }
]);

const handleBack = () => {
    router.back();
}

const goToOrder = () => {
    // 清除支付信息
    paymentStore.clearPayInfo();
    // 跳转到订单页面
    router.push('/personCenter/Center?personCenterValue=5');
}
</script>
<style lang="scss" scoped>
.integralPay {
    width: 1000px;
    margin: 0 auto;
    .integralPay-header {
        width: 100%;
        height: 64px;
        padding: 20px;
        display: flex;
        align-items: center;
        justify-content: center;
        position: relative;

        .left {
            display: flex;
            position: absolute;
            top: 50%;
            left: 20px;
            transform: translate(0px, -50%);
            align-items: center;
            cursor: pointer;

            .leftBack {
                font-size: 14px;
                font-weight: 400;
                color: #333333;
            }
        }

        .header-center {
            color: #333333;
            font-size: 18px;
            font-weight: 600
        }
    }
    .integralPay-order {
        width: 100%;
        height: 100%;
        background: #FFFFFF;
        padding: 20px;

        .order-title {
            font-size: 18px;
            font-weight: 600;
            color: #333333;
        }
        .order-content {
            width: 100%;
            height: 100%;
            background: #FFFFFF;
            margin-top: 20px;
            .order-content-item {
                width: 100%;
                height: 100%;
                background: #FFFFFF;
                display: flex;
                justify-content: space-between;
                .order-content-left {
                    flex: 1;
                    margin-right: 30px;
                    display: flex;
                    .order-content-left-img {
                        margin-right: 30px;
                        min-width: 95px;
                        height: 76px;
                        img {
                            min-width: 95px;
                            height: 76px;
                        }
                    }
                    .order-content-title {
                        // width: calc(100% - 95px - 30px - 200px);
                        font-size: 16px;
                        font-weight: 400;
                        color: #333333;
                    }  
                } 
                .order-content-right {
                    width: 180px;
                    display: flex;
                    justify-content: space-between;
                    .currency {
                        .currency-name {
                            font-size: 16px;
                            font-weight: 400;
                            color: #333333;
                        }
                        .currency-value {
                            font-size: 16px;
                            font-weight: 600;
                            color: #333333;
                        }
                    }   
                }
            }
        }
        .integral-info {
            width: 100%;
            height: 62px;
            background: #F5F5F5;
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 20px;
            border-radius: 8px;
            margin-top: 20px;
            .integral-info-left {
                font-size: 16px;
                font-weight: 600;
                color: #333333;
            }
            .integral-info-right {
                font-size: 14px;
                font-weight: 400;
                color: #126983;
                cursor: pointer;
            }
        }
        .total-price {
            width: 100%;    
            display: flex;
            justify-content: flex-end;
            align-items: center;
            margin-top: 20px;
            .total-price-left {
                font-size: 16px;
                font-weight: 600;
                color: #333333;
            }
        }
    }
    .amount-info {
        width: 100%;
        height: 100%;
        background: #FFFFFF;
        margin-top: 20px;
        display: flex;
        justify-content: flex-end;
        .amount-info-right {
            width: 340px;
            height: 100%;
            background: #FFFFFF;
            display: flex;
            flex-direction: column;
        }   
        .total-amount-item {
            width: 100%;
            height: 42px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 20px;
            .total-amount-item-left {
                width: 100px;
                text-align: right;
                font-size: 16px;
                font-weight: 400;
                color: #333333;
            }
            .total-amount-item-right {
                font-size: 16px;
                font-weight: 600;
                color: #333333;
                &.total-amount-item-right-red {
                    color: #FF0000;
                    font-size: 24px;
                    font-weight: 600;
                }
            }
        }   
    }       
    .payment-method {
        width: 100%;
        height: 100%;
        background: #FFFFFF;
        margin-top: 20px;
        .method-header {
            width: 100%;
            height: 42px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 20px;
            .payment-amount-title {
                font-size: 16px;
                font-weight: 600;
                color: #333333;
                .payment-amount-title-red {
                    color: #FF0000;
                    font-size: 24px;
                    font-weight: 600;
                }   
            }
            .payment-amount-right {
                font-size: 14px;
                font-weight: 400;
                color: #333333;
                .payment-amount-right-phone {
                    color: #126983;
                    font-size: 16px;
                    font-weight: 400;
                }
            }
        }           
        .payment-method-container {
            width: 100%;
            height: 100%;
            background: #FFFFFF;
            padding: 20px;
            .payment-method-item {
                width: 100%;
                height: 52px;
                display: flex;
                align-items: center;
                border: 1px solid #cccccc;
                border-radius: 8px;
                padding-left: 20px;
                margin-bottom: 10px;
                .payment-method-item-left {
                    margin-right: 20px; 
                    img {
                        width: 100%;
                        height: 100%;
                    }
                }
                .payment-method-item-right {
                    font-size: 16px;
                    font-weight: 600;
                    color: #333333;
                    display: flex;
                    align-items: center;
                    margin-left: 15px;
                    img {
                        width: 32px;
                        height: 32px;
                        margin-right: 10px;
                    }
                }
            }   
        }     
        .submit-pay {
            width: 164px;
            height: 42px;
            background: #126983;
            border-radius: 4px;
            color: #FFFFFF;
            font-size: 16px;
            font-weight: 400;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
        }
    }  
    .payment-options {
        margin-bottom: 30px;
        padding: 20px;
    }
  
  .payment-option {
    display: flex;
    align-items: center;
    padding: 15px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    margin-bottom: 15px;
    cursor: pointer;
    
    &.active {
      border-color: #126983;
      background: #FAFEFF;
    }
  }
  
  .radio-button {
    width: 18px;
    height: 18px;
    border-radius: 50%;
    border: 1px solid #126983;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-right: 10px;
    
    .inner-circle {
      width: 10px;
      height: 10px;
      border-radius: 50%;
      background-color: #126983;
    }
  }
  
  .payment-icon {
    width: 24px;
    height: 24px;
    margin-right: 10px;
    background-size: contain;
    background-repeat: no-repeat;
    
    &.alipay {
      background-image: url('/static/zhi.png');
    }
    
    &.wechat {
      background-image: url('/static/w.png');
    }
  }  
  // 云豆弹窗样式
  .bean-dialog-content {
    padding: 10px 0;
  }
  
  .bean-description {
    margin-bottom: 20px;
    line-height: 1.5;
    color: #666;
  }
  
  .dialog-footer {
    display: flex;
    justify-content: center;
  }
  
  // 支付弹窗样式
  .payment-dialog-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20px 0;
  }
  
  .qr-code {
    width: 200px;
    height: 200px;
    background-color: #eee;
    margin-bottom: 20px;
  }
  
  .payment-amount {
    font-size: 18px;
    color: #f56c6c;
    font-weight: 500;
    margin-top: 10px;
  }
  
  // 支付成功弹窗样式
  .success-dialog-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20px 0;
  }
  
  .success-icon {
    margin-bottom: 15px;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 60px;
    height: 60px;
    border-radius: 50%;
    background-color: #52C41A;
  }
  
  .success-dialog-content h3 {
    margin-bottom: 15px;
    font-weight: 500;
  }
  
  .success-dialog-content p {
    margin-bottom: 20px;
    color: #666;
  }
}
:deep(.el-dialog__header.show-close) {
    padding-right: 0px;
}
</style>